// ResourceManager.ts

import { Config } from "../Config";

class ResourceManager {
    private loadingResources: number;
    private loadedResources: { [key: string]: cc.Asset };
    private constructor() {
        this.loadingResources = 0;
        this.loadedResources = {};
    }

    //单例
    private static _ins: ResourceManager;
    public static get ins(): ResourceManager {
        if (this._ins == null) {
            this._ins = new ResourceManager();
        }
        return this._ins;
    }
    /**
     * @path 文件路径
     * @type 文件类型
     * @bundleName bundle名字
     */
    public loadRomote<T extends cc.Asset>(remoteUrl: string, T: typeof cc.Asset): Promise<T> {
        return new Promise((resolve, reject) => {
            const onComplete = (err: Error | null, resource: T) => {
                this.loadingResources--;
                if (err) {
                    reject(err);
                } else {
                    resolve(resource);
                }
            };
            cc.assetManager.loadRemote(remoteUrl, {ext: '.png'},onComplete);
        });
    }
    /**
     * @path 文件路径
     * @type 文件类型
     * @bundleName bundle名字
     */
    public loadResource<T extends cc.Asset>(path: string, type: typeof cc.Asset, bundleName?: string): Promise<T> {
        return new Promise((resolve, reject) => {
            if (this.loadedResources[path]) {
                resolve(this.loadedResources[path] as T);
            } else {
                this.loadingResources++;
                const onComplete = (err: Error | null, resource: cc.Asset) => {
                    this.loadingResources--;
                    if (err) {
                        reject(err);
                    } else {
                        this.loadedResources[path] = resource;
                        resolve(resource as T);
                    }
                };
                let bundle: cc.AssetManager.Bundle | undefined;
                if (bundleName) {
                    bundle = cc.assetManager.getBundle(bundleName);
                    if (!bundle) {
                        cc.assetManager.loadBundle(bundleName, async (err, bundle1) => {
                            if (err) {
                                console.error("分包加载失败", err);
                                return
                            }
                            bundle1.load(path, type, onComplete);
                        })
                        return
                    }
                }

                if (bundle) {
                    bundle.load(path, type, onComplete);
                } else {
                    cc.resources.load(path, type, onComplete);
                }
            }
        });
    }
    /**
     * @path 文件路径
     * @type 文件类型
     * @bundleName bundle名字
     */
    // public loadDirResource<T extends cc.Asset>(path: string, type: typeof cc.Asset, bundleName?: string): Promise<T> {
    //     return new Promise((resolve, reject) => {
    //         if (this.loadedResources[path]) {
    //             resolve(this.loadedResources[path] as T);
    //         } else {
    //             this.loadingResources++;
    //             const onComplete = (err: Error | null, resource: cc.Asset) => {
    //                 this.loadingResources--;
    //                 if (err) {
    //                     reject(err);
    //                 } else {
    //                     this.loadedResources[path] = resource;
    //                     resolve(resource as T);
    //                 }
    //             };
    //             let bundle: cc.AssetManager.Bundle | undefined;
    //             if (bundleName) {
    //                 bundle = cc.assetManager.getBundle(bundleName);
    //                 if (!bundle) {
    //                     cc.assetManager.loadBundle(bundleName, async (err, bundle1) => {
    //                         if (err) {
    //                             console.error("分包加载失败", err);
    //                             return
    //                         }
    //                         bundle1.load(path, type, onComplete);
    //                     })
    //                     return
    //                 }
    //             }

    //             if (bundle) {
    //                 bundle.load(path, type, onComplete);
    //             } else {
    //                 cc.resources.loadDir(path, type, onComplete);
    //             }
    //         }
    //     });
    // }
    /**
     * 释放资源 
     * @path 资源路径
     * */
    public releaseResource(path: string): void {
        if (this.loadedResources[path]) {
            cc.resources.release(path);
            delete this.loadedResources[path];
        }
    }
    /**释放所有资源 */
    public releaseAllResources(): void {
        cc.assetManager.releaseAll();
        this.loadedResources = {};
    }
    /**加载状态 */
    public isLoading(): boolean {
        return this.loadingResources > 0;
    }
    public async loadGameRes(){
        let leng = 5;
        for (let i = 1; i <= leng; i++) {
            let s:cc.SpriteFrame = await ResourceManager.ins.loadResource("head/head"+i,cc.SpriteFrame);
            // console.log(s)
            Config.headimgs.push(s);
            let bl = i/leng;
            Config.loading.press("加载中..."+Math.floor(bl*100)+"%",bl);
            // await new Promise(res=>setTimeout(res,300));
        }
        
        cc.resources.loadDir("anima",sp.SkeletonData,(finish,total,item)=>{
            // console.log(finish,total)
        },(err,asset)=>{
            // console.log(err,asset)
        });
        cc.resources.loadDir("audio",cc.AudioClip,(finish,total,item)=>{
            // console.log(finish,total)
        },(err,asset)=>{
            // console.log(err,asset)
        });
        let peiyin = cc.sys.localStorage.getItem('gamemusic');
        if (peiyin == "nan" || peiyin == "nv") {
            Config.peiyin = peiyin;
        }

    }
}

export default ResourceManager;  